package com.rfid.a252robot.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.EditText;

import com.google.gson.Gson;
import com.rfid.a252robot.R;
import com.rfid.a252robot.admin.AdminHomeActivity;
import com.rfid.a252robot.admin.DailyWorkService;
import com.rfid.a252robot.base.BaseActivity;
import com.rfid.a252robot.base.BasePresenter;
import com.rfid.a252robot.event.ZhaoHuiEvent;
import com.rfid.manager.DoorBoxManager;
import com.rfid.manager.LogViewManager;
import com.rfid.manager.TaskManager;
import com.rfid.mqtt.MqttManager;
import com.rfid.sockethelper.IOHelper;
import com.rfid.sockethelper.SocketBase;
import com.rfid.socketio.SocketIOClient;
import com.rfid.util.FileUtil1;
import com.rfid.util.LogUtils;
import com.rfid.util.Util;
import com.rfid.webp2plib.SignalClient;
import com.rfid.webp2plib.User;
import com.spectre.generate.ConfigManager;
import com.spectre.generate.exception.ConfigFileNotFoundException;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {

    SocketIOClient mClient;
    View mBanner;
    ZhaoHuiEvent mZhaoHuiEvent;
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            String tip = "如需借还，请点击屏幕或请说我要借书、我要还书、停车";
            if (mZhaoHuiEvent != null) {
                if (mZhaoHuiEvent.isZhaoHui()) {
                    tip = "正在被召回，暂停服务";
                }
            }
            MqttManager.INSTANCE.sendVoice(tip);
            mHandler.sendEmptyMessageDelayed(0,20000);
            return false;
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBanner = findViewById(R.id.bottom_banner);
        LogUtils.v("log","MainActivity onCreate");
        DoorBoxManager.INSTANCE.prepareReadWrite();
//        Mock.setMockDataToDb();
        MqttManager.INSTANCE.init(this);

        Display display = getWindowManager().getDefaultDisplay();
        System.out.println(display.getWidth() + ":" + display.getHeight());
        System.out.println(getResources().getDisplayMetrics().density);
        System.out.println(Util.getScreenHeight());
        mBanner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showPassWordDialog();
                return false;
            }
        });
        TaskManager.instance().startCheckTask();

        mClient = new SocketIOClient(new SocketBase.OnReceiveListener() {
            @Override
            public void onReceived(String s, short cmd, CharSequence... text) {
                if (cmd == IOHelper.CMD_QUERY_CONFIGS) {
                    List<String> configs = new ArrayList<>();
                    configs.add("global");
                    configs.add("acs");
                    configs.add("charge");
                    Gson gson = new Gson();
                    mClient.sendConfigNames(gson.toJson(configs));
                } else if (cmd == IOHelper.CMD_PULL_CONFIG) {
                    String json = FileUtil1.readFile("/sdcard/robot/config/" + text[0] + ".json");
                    mClient.sendConfig(text[0].toString(), json);
                } else if (cmd == IOHelper.CMD_SET_CONFIG) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String name = text[0].toString();
                            String value = text[1].toString();
                            System.out.println("onConfig txt = " + value);
                            FileUtil1.writeFile("/sdcard/robot/config/" + name + ".json",value);
                            try {
                                ConfigManager.INSTANCE.init();
                            } catch (ConfigFileNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            }

            @Override
            public void onConnect(String s, boolean b) {

            }
        });
        mClient.setUserListener(new SignalClient.UserListener() {
            @Override
            public void onLogin(String s, List<User> list) {
            }

            @Override
            public void onConnect(String s) {
                mClient.login(MainActivity.this, ConfigManager.INSTANCE.getGlobalConfig().getDeviceId());
            }

            @Override
            public void onDisconnect() {

            }
        });
        mClient.connectSignalServer();

        Intent intent = new Intent();
        intent.setClass(this, DailyWorkService.class);
        startService(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onZhaoHui(ZhaoHuiEvent event) {
        mZhaoHuiEvent = event;
    }

    @Override
    protected int getCountDownTime() {
        return -1;
    }

    private void showPassWordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_password_layout,null);
        EditText editText = view.findViewById(R.id.edit);
        builder.setView(view);
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                setSystemUIVisible(false);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog1, int which) {
                if (editText != null) {
                    String pwd = editText.getText().toString();
                    if ("shrfid".equals(pwd)) {
                        Util.startActivity(MainActivity.this,AdminHomeActivity.class);
                    }
                }
            }
        });
        Dialog dialog =  builder.create();
        dialog.show();
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogViewManager.INSTANCE.init(this);
        LogViewManager.INSTANCE.show();
        boolean r = LogViewManager.INSTANCE.checkFloatPermission(this);
        if (!r) {
            LogViewManager.INSTANCE.requestFloatPermission(this);
        }
        MqttManager.INSTANCE.queryStatus();
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0,5000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mHandler.removeMessages(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogViewManager.INSTANCE.hide();
        mHandler.removeMessages(0);
        mClient.release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogViewManager.INSTANCE.onActivityResult(this,requestCode,resultCode,data);
    }

    public void borrow(View view) {
        System.out.println("borrow");
        Util.startActivity(this, BookListActivity.class);
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        System.out.println(metrics.widthPixels + ":" + metrics.heightPixels + ":" + metrics.density);

//        DoorBoxManager.INSTANCE.setListener(new DoorBoxManager.Listener() {
//            @Override
//            public void onLockOpen(int num, boolean success) {
//                System.out.println("onLockOpen num = " + num + ",success = " + success);
//            }
//
//            @Override
//            public void onLockOpenStatus(int num, boolean open) {
//                System.out.println("onLockOpenStatus num = " + num + ",open = " + open);
//            }
//        });
//        DoorBoxManager.INSTANCE.openLock((byte) 2);
//        DoorBoxManager.INSTANCE.queryOpenStatus((byte) 3);
    }

    public void restore(View view) {
//        NewReadTagManager.INSTANCE.startReadTag();
//        NewReadTagManager.INSTANCE.selectAntenna(2);

//        ReadTagManager.INSTANCE.prepareReadTag();
//        ReadTagManager.INSTANCE.selectAntenna(1);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                List<TagEntity> tagEntities =  ReadTagManager.INSTANCE.readTags();
//                System.out.println(tagEntities);
//                try {
//                    Thread.sleep(500);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                tagEntities =  ReadTagManager.INSTANCE.readTags();
//                System.out.println(tagEntities);
//            }
//        }).start();
//        LogViewManager.INSTANCE.show();
//        MqttManager.INSTANCE.scanQr();
//        BookManager.INSTANCE.searchBookWithBarcode("600183")
//                .subscribe(new Consumer<BookBean>() {
//                    @Override
//                    public void accept(BookBean bookBean) throws Exception {
//
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        LogUtils.e(throwable);
//                    }
//                });
        Util.startActivity(this, RestoreActivity.class);
//        Util.startActivity(this, WebViewActivity.class);
//        MqttManager.INSTANCE.getMapInfo();
//        MqttManager.INSTANCE.startMoveTask("1663782474265440258");
//        MqttManager.INSTANCE.pauseRobot("3e4e418874a44660a18edf1d04674050");
    }

    public void banzheng(View view) {
        Util.startActivity(this,BanZhengQrActivity.class);
    }

    public void qa(View view) {
        Util.startActivity(this,QAActivity.class);
    }
}